package com.system.login.controller;


import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Properties;

/**
 * 2019/10/8
 * <p>
 * 图片验证码--> all
 */

@Controller
public class CaptchaControl {
    @Autowired
    private DefaultKaptcha kaptcha;//添加spring依赖


    @RequestMapping(path = "/captcha")//处理htttp头信息
    public void getCaptcha(HttpServletResponse response, HttpSession session) throws IOException {

        //Set to expire far in the past------设置HTTP Cache 响应头
        response.setDateHeader("Expires", 0);
        //Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store,no-cache,must-revalidate");
        //Set IE extended HTTP/1.1 no-chae headers(ues addHeader)
        response.addHeader("Cache-Control", "post-check=0,pre-check=0");
        //Set standard Http/1.0 no-chae header
        response.setHeader("Pragma", "no-cache");


        //return a jpeg-----设置HTTP内容格式，即请求到图片格式内容
        response.setContentType("image/png");


        //create the text for the image-----创建随机数
        String capText = kaptcha.createText();
        //store the text in the session
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);


        //create the image with the text
        BufferedImage bi = kaptcha.createImage(capText);
        //write the data out
        ServletOutputStream out = response.getOutputStream();//抛出异常
        ImageIO.write(bi, "png", out);

        try {
            out.flush();//----普通i/o流输出
        } finally {
            out.close();
        }


    }

    /**
     * copy来的
     *
     * @return
     */

    @Bean//依靠他可以在启动spring时创建一个springbean的实例
    public DefaultKaptcha initKapacha() {
        DefaultKaptcha kaptcha = new DefaultKaptcha();
        Properties properties = new Properties();
        properties.put(Constants.KAPTCHA_IMAGE_HEIGHT, "50");
        properties.put(Constants.KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, "5");
        properties.put(Constants.KAPTCHA_TEXTPRODUCER_CHAR_STRING, "0123456789abcd");
        //properties.put(Constants.KAPTCHA_IMAGE_HEIGHT,"40");

        Config config = new Config(properties);
        kaptcha.setConfig(config);
        return kaptcha;
    }//复制进来的


}
